from django import forms
from microerp.apps.product.models import Product


'''
新建产品 Form
'''
class ProductForm(forms.Form):
	code = forms.CharField(max_length=20,required=False)	#产品编号
	name = forms.CharField(max_length=20,required=True)	#产品名称
	kind = forms.IntegerField(required=True)				#产品类型
	img = forms.CharField(required=False)					#产品图片
	state = forms.IntegerField(required=False)			#产品状态(0-无库存，1-正常，2-禁用)
	inventory = forms.FloatField(required=True,error_messages={'required':u'库存不能为空值','invalid':u'库存应为 数字 或 小数'})#产品库存
	cost = forms.FloatField(required=False,error_messages={'invalid':u'进价应为 数字 或 小数'})#产品进价
	price = forms.FloatField(required=False,error_messages={'invalid':u'建议售价应为 数字 或 小数'})#建议售价
	producer = forms.CharField(required=False)			#产地
	notes = forms.CharField(required=False,max_length=1000,error_messages={'max_length':u'超过最大字符串1000'}, widget= forms.Textarea(attrs={'cols': 80, 'rows': 20}))	#产品说明

	def clean(__self__):
		cleaned_data = __self__.cleaned_data
		name = cleaned_data.get("name")
		if name:
			count = Product.objects.filter(name=name).count()
			#如果存在相同的产品名称的话，验证失败
			if count is not 0:
				msg = u'已经存在相同的产品了'
				__self__.errors["name"] = __self__.error_class([msg])
	
		img = cleaned_data.get("img")
		#如果不存在图标的话，指定图标
		if not img:
			cleaned_data["img"] = '/static/img/table-img.png'

		#如果不设定库存的话，产品状态就是无库存
		inventory = cleaned_data.get("inventory")
		state = cleaned_data.get("state")
		if int(inventory) is 0:
			cleaned_data["state"] = 0
		elif state == 2:
			cleaned_data["state"] = 2
		else:
			cleaned_data["state"] = 1

		return cleaned_data



